//
//  YYTabbar.swift
//  WeiBo001
//
//  Created by geduo on 2018/5/9.
//  Copyright © 2018年 geduo. All rights reserved.
//

import UIKit


protocol YYTabBarDelegate:NSObjectProtocol {
    func didSelectedComposeButton()
}

class YYTabbar: UITabBar {
    
    weak var hmDelegate :YYTabBarDelegate?
    
    var composeButtonClosure:(()->())?
    
    
    private lazy var composeButton: UIButton = {
        let button = UIButton()
        
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal)
       button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .highlighted)

        
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal)
        
        button.addTarget(self, action: #selector(composeButtonAction), for: .touchUpInside)
        
        button.sizeToFit()
        
        return button
    }()
    
    @objc func composeButtonAction() {
        composeButtonClosure?()
        
        hmDelegate?.didSelectedComposeButton()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI(){
        addSubview(composeButton)
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //思考： 该方法何时调用的？？？  
        composeButton.center.x = frame.size.width/2
        composeButton.center.y = frame.size.height/2
        
        let itemWidth = frame.size.width / 5
        
        var index = 0
        for subView:UIView in self.subviews {
            if subView.isKind(of: NSClassFromString("UITabBarButton")!){
                subView.frame.size.width = itemWidth
//                subView.backgroundColor = UIColor.red
                
                subView.frame.origin.x = CGFloat(index) * itemWidth
                
                index += 1
                if index == 2{
                    index += 1
                }
                
            }
        }
    }
}
